'use strict';

import Base from './base.js';

export default class extends Base {

  async listAction(){
    let model = this.model("user");
    let data = await model.page(this.get("page"), 10).countSelect();
    //data.pageSize=10;
    //data.total=data.data.length;
    //data.page=Math.ceil(total/pageSize);
    //data.curPage=this.get("page")
    this.success(data);
  }

  async delAction(){
    let model = this.model("user");
    let ids=this.post("ids[]");
    console.log(ids);
    //let affectedRows = await model.where({id: ["IN", ids]}).delete();
    this.success(ids);
  }

  /**
   * 用户注册
   */
  async registerAction(t) {
    let postData=JSON.parse(this.post("postData"));
    await this.setBaseInfo(postData,"add");
    let model = this.model("user");
    //密码加密
    postData.psw=think.md5(postData.psw);
    try {
      postData.id= await model.add(postData);
      postData.token=await this.getHeaderToken(postData.id,postData.name);
      return this.success(postData);
    } catch (err) {
      think.log(err);
      return this.fail("SERVER_INVALID");
    }
  }

  /**
   * 用户登录
   */
  async loginAction() {
    let postData=JSON.parse(this.post("postData"));
    let model = this.model("user");
    let data = await model.where({
      phone: postData.phone,
      psw: think.md5(postData.psw)
    }).find();
    if (!think.isEmpty(data)) {
      let token=await this.getHeaderToken(data.id,data.name);
      data.toekn=token;
      var userInfo=data;
      await this.session("userInfo", userInfo);
      return this.success(userInfo);
    } else {
      return this.fail("NEED_LOGIN");
    }
  }


  /**
   * 获取登录用户信息
   */
  async getUserInfoAction(){
    let userInfo=await this.getUserInfo();
    return this.success(userInfo);
  }
}
